﻿using ServiceCore.WebApi.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServiceCore.Utility.Extension
{
    public static class UtilityLog
    {
        #region 写日志到客户端文件

        /// <summary>
        /// 写日志到客户端文件
        /// </summary>
        /// <param name="logContext">日志内容</param>
        /// <param name="path">存放的目录</param>
        /// <param name="saveDay">保留天数</param>
        /// <param name="IsWriteDateTime">是否要加是日期时间</param>
        public static void LogWriteClient(this string logContext, string path, int saveDay = 180, bool IsWriteDateTime = true, bool IsOver = false, string filename = "")
        {
            logContext.LogWriteTxt(path, saveDay, IsWriteDateTime, true, IsOver: IsOver, filename: filename);
        }

        #endregion 写日志到客户端文件

        #region 写日志到服务端文件

        /// <summary>
        /// 写日志到服务端文件
        /// </summary>
        /// <param name="logContext">日志内容</param>
        /// <param name="path">存放的目录</param>
        /// <param name="saveDay">保留天数</param>
        /// <param name="IsWriteDateTime">是否要加是日期时间</param>
        public static void LogWriteService(this string logContext, string path, int saveDay = 180, bool IsWriteDateTime = true, bool IsOver = false, string filename = "")
        {
            logContext.LogWriteTxt(path, saveDay, IsWriteDateTime, false, dirBase: "", IsOver: IsOver, filename: filename);
        }

        #endregion 写日志到服务端文件

        #region 写日志到txt文件

        /// <summary>
        /// 写日志到txt文件
        /// </summary>
        /// <param name="logContext"></param>
        /// <param name="path"></param>
        /// <param name="saveDay"></param>
        private static void LogWriteTxt(this string logContext, string path, int saveDay = 180, bool IsWriteDateTime = true, bool IsClient = false, string dirBase = "", bool IsOver = false, string filename = "")
        {
            if (string.IsNullOrEmpty(logContext))
                return;
            if (string.IsNullOrEmpty(dirBase))
                dirBase = StaticVar.HttpPath + StaticVar.PathSplitLine;

            UtilityFunction.LockExtension(() =>
            {
                dirBase = dirBase + path.Replace("\\", StaticVar.PathSplitLine);
                if (Directory.Exists(dirBase) == false)
                    Directory.CreateDirectory(dirBase);
                var file = dirBase + StaticVar.PathSplitLine + DateTime.Now.ToyyyyMMdd() + ".txt";
                if (string.IsNullOrEmpty(filename) == false)
                    file = dirBase + StaticVar.PathSplitLine + filename + ".txt";
                if (IsWriteDateTime)
                {
                    var logMsg = DateTime.Now.ToyyyyMMddHHmmssffff() + Environment.NewLine + "=====================================================" + Environment.NewLine + logContext;
                    logMsg += Environment.NewLine;
                    logMsg += Environment.NewLine;
                    if (IsOver == false)
                        File.AppendAllText(file, logMsg);
                    else
                        File.WriteAllText(file, logMsg);
                }
                else
                {
                    if (IsOver == false)
                        File.AppendAllText(file, logContext);
                    else
                        File.WriteAllText(file, logContext);
                }
            });

            try
            {
                if (IsOver)
                {
                    return;
                }
                //删除日志，保留最近半年的日志
                var files = new DirectoryInfo(dirBase).GetFiles("*.txt", SearchOption.TopDirectoryOnly).ToList();
                foreach (var d in files)
                {
                    var filedate = d.CreationTime;
                    var curtime = DateTime.Now.Date;
                    var span = curtime - filedate;
                    if (span.Days >= saveDay)
                    {
                        if (d.Attributes.ToString().IndexOf("ReadOnly") != -1)
                            d.Attributes = FileAttributes.Normal;
                        d.Delete();//直接删除其中的文件
                    }
                }
            }
            catch
            {
            }
        }

        #endregion 写日志到txt文件

        #region 读取指定文件内容

        /// <summary>
        /// 读取指定文件内容
        /// </summary>
        /// <param name="path">路径\netcore\W微信库 类似这样</param>
        /// <param name="filename">文件名称不包括扩展名</param>
        /// <returns></returns>

        public static string LogReadTxt(this string path, string filename)
        {
            var file = StaticVar.HttpPath + StaticVar.PathSplitLine + path + StaticVar.PathSplitLine + filename + ".txt";
            if (File.Exists(file))
            {
                var context = File.ReadAllText(file);
                return context;
            }
            else
                return "";
        }

        #endregion 读取指定文件内容

        #region 单文件写入

        /// <summary>
        /// 单文件写入
        /// </summary>
        /// <param name="logContext">要写入的内容</param>
        /// <param name="path">路径</param>
        /// <param name="filename">文件名</param>
        public static void LogWriteTxtSingle(this string logContext, string path, string filename, bool isDelete = false)
        {
            if (string.IsNullOrEmpty(logContext))
                return;
            var dirBase = StaticVar.HttpPath + StaticVar.PathSplitLine + path + StaticVar.PathSplitLine;
            if (Directory.Exists(dirBase) == false)
                Directory.CreateDirectory(dirBase);
            filename = dirBase + filename + ".txt";
            UtilityFunction.LockExtension(() =>
            {
                File.WriteAllText(filename, logContext);
            });
            if (isDelete)
            {
                //删除日志，保留最近半年的日志
                var files = new DirectoryInfo(dirBase).GetFiles("*.txt", SearchOption.TopDirectoryOnly).ToList();
                foreach (var d in files)
                {
                    var filedate = d.CreationTime;
                    var curtime = DateTime.Now.Date;
                    var span = curtime - filedate;
                    if (span.Days >= 5)
                    {
                        if (d.Attributes.ToString().IndexOf("ReadOnly") != -1)
                            d.Attributes = FileAttributes.Normal;
                        d.Delete();//直接删除其中的文件
                    }
                }
            }

        }

        #endregion 单文件写入

        #region 单文件写入

        /// <summary>
        /// 单文件写入
        /// </summary>
        /// <param name="logContext">要写入的内容</param>
        /// <param name="path">路径</param>
        /// <param name="filename">文件名</param>
        public static void LogWriteTxtSingleByte(this byte[] logContext, string path, string filename, bool isDelete = false)
        {
            if (logContext == null || logContext.Length == 0)
                return;
            var dirBase = StaticVar.HttpPath + StaticVar.PathSplitLine + path + StaticVar.PathSplitLine;
            if (Directory.Exists(dirBase) == false)
                Directory.CreateDirectory(dirBase);
            filename = dirBase + filename + ".txt";
            UtilityFunction.LockExtension(() =>
            {
                File.WriteAllBytes(filename, logContext);
            });
            if (isDelete)
            {
                //删除日志，保留最近半年的日志
                var files = new DirectoryInfo(dirBase).GetFiles("*.txt", SearchOption.TopDirectoryOnly).ToList();
                foreach (var d in files)
                {
                    var filedate = d.CreationTime;
                    var curtime = DateTime.Now.Date;
                    var span = curtime - filedate;
                    if (span.Days >= 5)
                    {
                        if (d.Attributes.ToString().IndexOf("ReadOnly") != -1)
                            d.Attributes = FileAttributes.Normal;
                        d.Delete();//直接删除其中的文件
                    }
                }
            }

        }

        #endregion 单文件写入
    }
}
